package org.lzy.shop.order

import android.os.Bundle
import android.text.TextUtils
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import com.alipay.sdk.app.PayTask
import kotlinx.coroutines.withContext
import org.lzy.shop.Constant
import org.lzy.shop.R
import org.lzy.shop.base.BaseMvvmActivity
import org.lzy.shop.databinding.ActivityPayorderBinding
import org.lzy.shop.util.ToastUtil
import org.lzy.shop.viewmodel.PayModel

/**
 * 支付
 */
class PayOrderActivity : BaseMvvmActivity<ActivityPayorderBinding, PayModel>({ ActivityPayorderBinding.inflate(it) }) {
    var goodsPrice: String? = null
    var goodsID: Int = 0

    override fun initView() {
        if (intent.extras != null) {
            val bundle = intent.extras
            goodsPrice = bundle!!.getString(Constant.GOODSPRICE)
            binding.actSubmitOrderNewTvOrderMoney.text = goodsPrice
            goodsID = bundle.getInt(Constant.GOODID)
        }
        setTitleText(getResString(R.string.pay_title))
    }

    override fun requestData() {

    }

    override fun initData() {
        mViewModel.payData.observeWithLifecycle(this) {
                payResponse ->
            dismissLoading()
            // 使用lifecycleScope启动协程，确保与Activity生命周期绑定
            lifecycleScope.launch {
                try {
                    // 在IO线程执行耗时的支付操作
                    val result = withContext(Dispatchers.IO) {
                        val alipay = PayTask(this@PayOrderActivity)
                        alipay.payV2(payResponse, true)
                    }

                    // 回到主线程处理UI相关的支付结果
                    withContext(Dispatchers.Main) {
                        handlePayResult(result)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    withContext(Dispatchers.Main) {
                        if (!isFinishing && !isDestroyed) {
                            showToast(getResString(R.string.net_error))
                        }
                    }
                }
            }
        }
    }

    /**
     * 处理支付结果
     * 注意：此方法必须在主线程调用
     */
    private fun handlePayResult(result: MutableMap<String?, String?>) {
        try {
            val resultStatus = result["resultStatus"] ?: "-1"
            if (!isFinishing && !isDestroyed) {
                // 处理支付状态
                if (TextUtils.equals(resultStatus, "9000")) {
                    // 支付成功
                    showToast(getResString(R.string.pay_success))
                    val bundle = Bundle()
                    bundle.putInt(Constant.ORDER_POSITION, 0)
                    startActivity(MyOrderActivity::class.java, bundle)
                } else if (TextUtils.equals(resultStatus, "8000")) {
                    // 支付结果确认中
                    showToast(getResString(R.string.pay_waiting))
                } else if (TextUtils.equals(resultStatus, "6001")) {
                    // 用户取消支付
                    showToast(getResString(R.string.pay_cancel))
                } else {
                    // 支付失败
                    showToast(getResString(R.string.pay_failed))
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            if (!isFinishing && !isDestroyed) {
                showToast(getResString(R.string.net_error))
            }
        }
    }

    override fun allClick() {
        binding.actSubmitOrderNewBtnGoPay.setOnClickListener {
            showLoading()
            mViewModel.pay(goodsID)
        }
    }
}